/**
 * ComposerToolbar - 输入工具栏组件
 * 
 * 提供文件上传、表情、代码、链接等快捷插入功能
 */

import { useState, useRef, useMemo } from 'react';
import { Image as ImageIcon, Smile, Code, Link as LinkIcon, Mic, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { PromptTemplatePicker } from '@/components/prompts/PromptTemplatePicker';
import { PromptVariableDialog } from '@/components/prompts/PromptVariableDialog';
import { PromptTemplateManager } from '@/lib/prompt-template-manager';
import type { PromptTemplate } from '@/types/prompt';

// ============================================================================
// 类型定义
// ============================================================================

export interface ComposerToolbarProps {
  onFileSelect?: (files: File[]) => void;
  onEmojiSelect?: (emoji: string) => void;
  onCodeInsert?: (code: string, language?: string) => void;
  onLinkInsert?: (url: string, text?: string) => void;
  onVoiceInput?: () => void;
  onPromptTemplateSelect?: (prompt: string) => void;
  disabled?: boolean;
  className?: string;
}

// ============================================================================
// 主组件
// ============================================================================

export function ComposerToolbar({
  onFileSelect,
  onEmojiSelect,
  onCodeInsert,
  onLinkInsert,
  onVoiceInput,
  onPromptTemplateSelect,
  disabled = false,
  className,
}: ComposerToolbarProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);
  const [codeInsertOpen, setCodeInsertOpen] = useState(false);
  const [linkInsertOpen, setLinkInsertOpen] = useState(false);
  const [promptPickerOpen, setPromptPickerOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<PromptTemplate | null>(null);

  // 初始化提示词模板管理器
  const promptManager = useMemo(() => new PromptTemplateManager(), []);
  const templates = useMemo(() => promptManager.getAllTemplates(), [promptManager]);

  // 文件选择处理
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0 && onFileSelect) {
      onFileSelect(files);
    }
    // 重置 input，允许选择相同的文件
    e.target.value = '';
  };

  // 处理模板选择
  const handleTemplateSelect = (template: PromptTemplate) => {
    if (template.variables.length === 0) {
      // 无变量，直接使用
      onPromptTemplateSelect?.(template.template);
      promptManager.recordUsage(template.id);
      setPromptPickerOpen(false);
    } else {
      // 有变量，显示变量填写对话框
      setSelectedTemplate(template);
      setPromptPickerOpen(false);
    }
  };

  // 处理变量填写完成
  const handleVariableDialogConfirm = (filledPrompt: string, values: Record<string, any>) => {
    onPromptTemplateSelect?.(filledPrompt);
    if (selectedTemplate) {
      promptManager.recordUsage(selectedTemplate.id);
    }
    setSelectedTemplate(null);
  };

  return (
    <div className={cn('flex items-center gap-1', className)}>
      <TooltipProvider>
        {/* 提示词模板按钮 */}
        <Popover open={promptPickerOpen} onOpenChange={setPromptPickerOpen}>
          <Tooltip>
            <TooltipTrigger asChild>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  disabled={disabled}
                >
                  <Sparkles className="h-4 w-4" />
                </Button>
              </PopoverTrigger>
            </TooltipTrigger>
            <TooltipContent>
              <p>提示词模板</p>
            </TooltipContent>
          </Tooltip>
          <PopoverContent className="w-[600px] h-[500px] p-0" align="start">
            <PromptTemplatePicker
              templates={templates}
              onSelect={handleTemplateSelect}
              onClose={() => setPromptPickerOpen(false)}
            />
          </PopoverContent>
        </Popover>

        {/* 变量填写对话框 */}
        {selectedTemplate && (
          <Popover open={true} onOpenChange={(open) => !open && setSelectedTemplate(null)}>
            <PopoverContent className="w-[600px] h-[600px] p-0" align="start">
              <PromptVariableDialog
                template={selectedTemplate}
                onConfirm={handleVariableDialogConfirm}
                onCancel={() => setSelectedTemplate(null)}
              />
            </PopoverContent>
          </Popover>
        )}

        {/* 图像上传按钮 */}
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={() => fileInputRef.current?.click()}
              disabled={disabled}
            >
              <ImageIcon className="h-4 w-4" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>
            <p>上传图片 (支持拖拽和粘贴)</p>
          </TooltipContent>
        </Tooltip>

        {/* 隐藏的文件输入 */}
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept="image/png,image/jpeg,image/jpg,image/webp,image/gif"
          className="hidden"
          onChange={handleFileSelect}
          disabled={disabled}
        />

        {/* 表情选择器 */}
        <Popover open={emojiPickerOpen} onOpenChange={setEmojiPickerOpen}>
          <Tooltip>
            <TooltipTrigger asChild>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  disabled={disabled}
                >
                  <Smile className="h-4 w-4" />
                </Button>
              </PopoverTrigger>
            </TooltipTrigger>
            <TooltipContent>
              <p>插入表情</p>
            </TooltipContent>
          </Tooltip>
          <PopoverContent className="w-80" align="start">
            <EmojiPicker
              onSelect={(emoji) => {
                onEmojiSelect?.(emoji);
                setEmojiPickerOpen(false);
              }}
            />
          </PopoverContent>
        </Popover>

        {/* 代码插入 */}
        <Popover open={codeInsertOpen} onOpenChange={setCodeInsertOpen}>
          <Tooltip>
            <TooltipTrigger asChild>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  disabled={disabled}
                >
                  <Code className="h-4 w-4" />
                </Button>
              </PopoverTrigger>
            </TooltipTrigger>
            <TooltipContent>
              <p>插入代码</p>
            </TooltipContent>
          </Tooltip>
          <PopoverContent className="w-96" align="start">
            <CodeInsert
              onInsert={(code, language) => {
                onCodeInsert?.(code, language);
                setCodeInsertOpen(false);
              }}
              onCancel={() => setCodeInsertOpen(false)}
            />
          </PopoverContent>
        </Popover>

        {/* 链接插入 */}
        <Popover open={linkInsertOpen} onOpenChange={setLinkInsertOpen}>
          <Tooltip>
            <TooltipTrigger asChild>
              <PopoverTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  disabled={disabled}
                >
                  <LinkIcon className="h-4 w-4" />
                </Button>
              </PopoverTrigger>
            </TooltipTrigger>
            <TooltipContent>
              <p>插入链接</p>
            </TooltipContent>
          </Tooltip>
          <PopoverContent className="w-96" align="start">
            <LinkInsert
              onInsert={(url, text) => {
                onLinkInsert?.(url, text);
                setLinkInsertOpen(false);
              }}
              onCancel={() => setLinkInsertOpen(false)}
            />
          </PopoverContent>
        </Popover>

        {/* 语音输入（未来功能） */}
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={onVoiceInput}
              disabled={true} // 暂时禁用
            >
              <Mic className="h-4 w-4" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>
            <p>语音输入（即将推出）</p>
          </TooltipContent>
        </Tooltip>
      </TooltipProvider>
    </div>
  );
}

// ============================================================================
// 表情选择器
// ============================================================================

interface EmojiPickerProps {
  onSelect: (emoji: string) => void;
}

function EmojiPicker({ onSelect }: EmojiPickerProps) {
  const commonEmojis = [
    '😀', '😃', '😄', '😁', '😅', '😂', '🤣', '😊',
    '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘',
    '👍', '👎', '👌', '✌️', '🤞', '🤝', '👏', '🙏',
    '💪', '🦾', '🤚', '👋', '🤟', '✋', '🖐️', '👊',
    '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍',
    '💯', '💢', '💥', '💫', '💦', '💨', '🕳️', '💬',
    '🔥', '⭐', '🌟', '✨', '⚡', '💡', '🎉', '🎊',
    '🚀', '⚙️', '🔧', '🔨', '⚒️', '🛠️', '⚔️', '🔪',
  ];

  return (
    <div className="space-y-2">
      <div className="text-sm font-medium">选择表情</div>
      <div className="grid grid-cols-8 gap-2">
        {commonEmojis.map((emoji, index) => (
          <button
            key={index}
            type="button"
            onClick={() => onSelect(emoji)}
            className="flex h-8 w-8 items-center justify-center rounded hover:bg-accent text-lg transition-colors"
          >
            {emoji}
          </button>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// 代码插入器
// ============================================================================

interface CodeInsertProps {
  onInsert: (code: string, language?: string) => void;
  onCancel: () => void;
}

function CodeInsert({ onInsert, onCancel }: CodeInsertProps) {
  const [code, setCode] = useState('');
  const [language, setLanguage] = useState('typescript');

  const languages = [
    'typescript', 'javascript', 'python', 'java', 'go',
    'rust', 'c', 'cpp', 'csharp', 'php',
    'ruby', 'swift', 'kotlin', 'scala', 'html',
    'css', 'sql', 'bash', 'json', 'yaml',
  ];

  const handleInsert = () => {
    if (code.trim()) {
      onInsert(code, language);
      setCode('');
    }
  };

  return (
    <div className="space-y-3">
      <div className="text-sm font-medium">插入代码</div>
      
      {/* 语言选择 */}
      <select
        value={language}
        onChange={(e) => setLanguage(e.target.value)}
        className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
      >
        {languages.map((lang) => (
          <option key={lang} value={lang}>
            {lang}
          </option>
        ))}
      </select>

      {/* 代码输入 */}
      <textarea
        value={code}
        onChange={(e) => setCode(e.target.value)}
        placeholder="粘贴或输入代码..."
        className="w-full min-h-[120px] rounded-md border border-input bg-background px-3 py-2 text-sm font-mono ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring resize-none"
      />

      {/* 操作按钮 */}
      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={onCancel}
        >
          取消
        </Button>
        <Button
          type="button"
          size="sm"
          onClick={handleInsert}
          disabled={!code.trim()}
        >
          插入
        </Button>
      </div>
    </div>
  );
}

// ============================================================================
// 链接插入器
// ============================================================================

interface LinkInsertProps {
  onInsert: (url: string, text?: string) => void;
  onCancel: () => void;
}

function LinkInsert({ onInsert, onCancel }: LinkInsertProps) {
  const [url, setUrl] = useState('');
  const [text, setText] = useState('');

  const handleInsert = () => {
    if (url.trim()) {
      onInsert(url.trim(), text.trim() || undefined);
      setUrl('');
      setText('');
    }
  };

  // 简单的 URL 验证
  const isValidUrl = (str: string) => {
    try {
      new URL(str);
      return true;
    } catch {
      return str.startsWith('http://') || str.startsWith('https://');
    }
  };

  const urlValid = !url || isValidUrl(url);

  return (
    <div className="space-y-3">
      <div className="text-sm font-medium">插入链接</div>
      
      {/* URL 输入 */}
      <div>
        <input
          type="url"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          placeholder="https://example.com"
          className={cn(
            "w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
            !urlValid && "border-destructive"
          )}
        />
        {!urlValid && (
          <p className="mt-1 text-xs text-destructive">
            请输入有效的 URL
          </p>
        )}
      </div>

      {/* 链接文本（可选） */}
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="链接文本（可选）"
        className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
      />

      {/* 操作按钮 */}
      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={onCancel}
        >
          取消
        </Button>
        <Button
          type="button"
          size="sm"
          onClick={handleInsert}
          disabled={!url.trim() || !urlValid}
        >
          插入
        </Button>
      </div>
    </div>
  );
}

